# -*- coding: utf-8 -*-
import requests#type: ignore
import json
import os
import time

TOKEN_FILE = 'token_info.json'  # 存储令牌和生成时间的文件
ak = "NHYYVR32PAHNBFZRURPX"
sk = "SlbMPJwmUQViEE9BeNK50BsteORqryR32EqjvGyh"
def get_token():
    # 检查文件是否存在
    if os.path.exists(TOKEN_FILE):
        with open(TOKEN_FILE, 'r') as f:
            token_info = json.load(f)
            token = token_info.get('token')
            generated_time = token_info.get('generated_time')

            # 检查令牌是否过期（超过一天）
            if time.time() - generated_time < 86400:  # 86400秒 = 1天
                return token

    # 生成新的令牌
    url = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"
    payload = json.dumps({
      "auth": {
        "identity": {
          "password": {
            "user": {
              "domain": {
                "name": "hw075471301"
              },
              "name": "hw075471302",
              "password": "142857Qaz"
            }
          },
          "methods": [
            "password"
          ]
        },
        "scope": {
          "project": {
            "name": "cn-north-4"
          }
        }
      }
    })
    headers = {
      'Content-Type': 'application/json',
      'Cookie': 'HWWAFSESID=e66439df3dcb22429c; HWWAFSESTIME=1738555050444'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    x_subject_token = response.headers.get("X-Subject-Token")
    print("REQUESTED TOKEN: " + x_subject_token[0:10])
    # 写入令牌和生成时间到文件
    with open(TOKEN_FILE, 'w') as f:
        json.dump({
            'generated_time': time.time(),
            'token': x_subject_token
        }, f)

    return x_subject_token

# 使用示例
if __name__ == '__main__':
    token = get_token()
    print(token[0:10])
